package cn.larry.common.utils.wx;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import cn.larry.common.exception.ServiceException;
import cn.larry.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.validation.constraints.NotNull;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * This is created,
 * but not necessarily updated by me.
 * Therefore, AUTHOR is useless.
 * 2024/4/28 09:17
 *
 * @Version 1.0
 */
@Slf4j
@Component
public class QywxUserTool {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取企业微信用户ID
     *
     * @param code        用户临时授权code
     * @param accessToken
     * @return
     */
    public String getQywxid(String code, String accessToken) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=" + accessToken + "&code=" + code;
//        log.info("请求微信：{}", url);
        String s = HttpUtil.get(url);
//        log.info("微信应答：{}", s);
        JSONObject jsonObject = JSONObject.parseObject(s);
        log.info("微信应答：{}", jsonObject);
        Object object = jsonObject.get("errcode");
        if (object != null && object.toString().equals("0")) {
            Object userid = jsonObject.get("userid");
            if (userid == null) {
                throw new ServiceException("获取用户信息异常");
            } else {
                return userid.toString();
            }
        } else {
            throw new ServiceException(jsonObject.get("errmsg").toString());
        }
    }

    /**
     * 手机号获取企业微信用户ID
     *
     * @param mobile
     * @return
     */
    public String getQywxId(String mobile, String accessToken) {
        if (StringUtils.isEmpty(mobile))
            return null;

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("mobile", mobile);

        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("token", accessToken);

        String postUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token={token}";
        Map<String, Object> result = restTemplate.postForObject(postUrl, JSON.toJSONString(paramMap), Map.class, uriVariables);
        log.info("微信应答：{}", result);
        if (0 != (int) result.get("errcode")) {
            log.error("getAllUserList error：" + result);
            return null;
        }
        return result.get("userid").toString();
    }

    /**
     * 组请求微信地址，用于获取用户授权code
     *
     * @param redirectUrl
     * @param corpId
     * @param agentId
     * @return
     */
    public String getSendreDirectUrl(String redirectUrl, String corpId, String agentId) {
        // 组请求微信
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
                + corpId;
        if (StringUtils.isNotEmpty(redirectUrl)) {
            try {
                url += "&redirect_uri="
                        + URLEncoder.encode(redirectUrl, "UTF-8");
            } catch (UnsupportedEncodingException e) {
            }
        }
        url += "&response_type=code&scope=snsapi_base&state=STATE&agentid="
                + agentId + "#wechat_redirect";
        log.info("reqUrl：{}", url);
        return url;

    }

    /**
     * 获取企业微信用户信息
     *
     * @param qywxId
     * @param accessToken
     * @return
     */
    public Map<String, Object> getUserInfo(@NotNull String qywxId, @NotNull String accessToken) {

        if (StringUtils.isEmpty(qywxId))
            return null;

        String getUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken
                + "&userid=" + qywxId;
        Map<String, Object> result = restTemplate.getForObject(getUrl, Map.class);
        log.info("微信应答：{}", result);
        if (0 != (int) result.get("errcode")) {
            log.error("punchCorrection error：" + result);
            return null;
        }
        return result;
    }

    /**
     * 获取离职成员的客户列表
     * 参考：https://developer.work.weixin.qq.com/document/path/96330
     *
     * @return （企业微信用户ID）
     */
    public Set<String> getUnassignedList(String token, String cursor, Integer pageSize) {

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("cursor", StringUtils.isEmpty(cursor) ? "" : cursor);
        paramMap.put("page_size", (pageSize > 0) ? pageSize : 1000);

        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("token", token);

        String postUrl = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_unassigned_list?access_token={token}";
        Map<String, Object> result = restTemplate.postForObject(postUrl, JSON.toJSONString(paramMap), Map.class, uriVariables);
        log.info("微信应答：{}", result);
        if (0 != (int) result.get("errcode")) {
            log.error("getUnassignedList error：" + result);
            throw new ServiceException(result.get("errmsg").toString());
        }
        Object object = result.get("info");
        if (object == null)
            return null;
        List<Map<String, Object>> unassignedList = (List<Map<String, Object>>) object;
//        log.info(unassignedList.get(0).toString());
        Set<String> userSet = new HashSet<>();
        for (Map<String, Object> userMap : unassignedList) {
            userSet.add(userMap.get("handover_userid").toString());
        }
        return userSet;
    }


}
